package com.atguigu.weixin.filter;

import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.atguigu.crud.bean.Wxuser;
import com.atguigu.crud.service.WxuserService;
import com.atguigu.weixin.kit.WeixinKit;
import com.atguigu.weixin.model.WeixinFianlValue;
import com.atguigu.weixin.model.WeixinUser;
import com.atguigu.weixin.servlet.BeanFactoryContext;

public class WeixinAuthFilter implements Filter {

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest hRequest = (HttpServletRequest)request;
		HttpServletResponse hResponse = (HttpServletResponse)response;
		  //先从seeion 里面获取登录信息对象
	    Wxuser tu=(Wxuser) hRequest.getSession().getAttribute("user");
	    System.out.println("############此处是过滤器的地方tu信息：");
		System.out.println(tu+"------用户seesion对象");
		if(tu==null) {
			String agent = hRequest.getHeader("User-Agent");
			System.out.println(agent);
			if(agent!=null&&agent.toLowerCase().indexOf("micromessenger")>=0) {
				String code = request.getParameter("code");
				String state = request.getParameter("state");
				System.out.println("#######code"+code);
				System.out.println("#######state"+state);
				if(code!=null&&state!=null&&state.equals("1")) {
					//通过Code获取openid来进行授权
					 WxuserService wxUserService = (WxuserService)BeanFactoryContext.getService("wxuserService");
					String openid = wxUserService.queryOpenidBycode(code);
					if(openid!=null) {
						 Wxuser u=wxUserService.loadByOpenid(openid);//调用微信接口
						if(u==null) {
							u= wxUserService.queryByOpenid(openid).getUser();
		    				wxUserService.add(u);
						} else {
							if(u.getStatus()==0) {
								u.setStatus(1);
		    					wxUserService.update(u);
							}
						}
						System.out.println("走到这里了@@@@@@@@@@@@@@@@——————————————————————————————————————————————————————————————————————");
						hRequest.getSession().setAttribute("user", u);
					}
				} else {
					String path = hRequest.getRequestURL().toString();
					String query = hRequest.getQueryString();
					if(query!=null) {
						path = path+"?"+query;
					}
					String uri = WeixinFianlValue.AUTH_URL;
					uri = uri.replace("APPID", WeixinFianlValue.APPID)
					   .replace("REDIRECT_URI",URLEncoder.encode(path, "UTF-8"))
					   .replace("SCOPE", "snsapi_base")
					   .replace("STATE", "1");
					hResponse.sendRedirect(uri);
//					System.out.println(uri);
					return;
				}
			}
		}
		chain.doFilter(hRequest, hResponse);
	}

	@Override
	public void destroy() {
		
	}

}
